import os,sys,inspect,socket,time
sys.path.append('/root/tornado-yw/mod/')
import sql
mysql=sql.Mysql('127.0.0.1','root','123456','kkk')
#
num = 0
class mon:
    def __init__(self):
        self.db_file='./db.json'
        self.data={}

    def getAmber(self):
        global num
        num+=1
        return num

    #def getDate(self):
    #    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())

    def getTimestrap(self):
        return int(time.time())
    
    def getProcess(self):
        return os.popen('ps -ef |wc -l').readlines()[0].split()[0]

    def getDisk(self):
        #return os.popen("df -h |grep '/$'").readlines()[0].split()
        data=[]
        disk=os.popen("df -h |grep '/$'").readlines()[0].split()
        data.append(disk[1].split('G')[0])
        data.append(disk[2].split('G')[0])
        return data

    def getMem(self):
        return os.popen('free -m').readlines()[1].split()[1:4]

    #def getSwap(self):
    #    return os.popen('free -m').readlines()[3].split()[1:]

    #def getLoad(self):
    #    return os.popen('uptime').readlines()[0].split()[-3:]

    #def getHost(self):
    #    return socket.gethostname()

    #def getUser(self):
    #    return os.popen('uptime').readlines()[0].split()[3]

    #def getRuntime(self):
    #    return os.popen('uptime').readlines()[0].split()[2]

    #def getSystem(self):
    #    return os.popen('cat /etc/redhat-release').readlines()[0].split('\n')[0]

    #def getKerner(self):
    #    return os.popen('uname -r').readlines()[0].split('\n')[0]


    def run(self):
        while 1:
            for fun in inspect.getmembers(self,predicate=inspect.ismethod):
                if fun[0][:3] == 'get':
                    #print fun[1]()
                    self.data[fun[0][3:]] = fun[1]()
            #return self.data
            print(self.data)
            process=int(self.data['Process'])
            memtotal=int(self.data['Mem'][0])
            memfree=int(self.data['Mem'][1])
            tms=int(self.data['Timestrap'])
            disktotal=float(self.data['Disk'][0])
            diskfree=float(self.data['Disk'][1])
            sql="INSERT INTO `hostinfo` (`time`,`cpuPercent`,`memTotal`,`memFree`,`diskTotal`,`diskFree`) VALUES (%s,%s,%s,%s,%s,%s)"
            mysql.write(sql%(tms,process,memtotal,memfree,disktotal,diskfree))
            #open(self.db_file,'a').write("%s\n" % self.data)
            time.sleep(5)
            break
if __name__ == "__main__":
     try:
         mon().run()
     except:
         print('\n')
         sys.exit(1)
